mod handlers;
mod models;
mod tests;
mod utils;

use actix_web::{get, middleware::Logger, post, web, web::Redirect, App, HttpServer};
use dotenvy::dotenv;
use handlers::{delete_markdown, get_markdown, get_markdown_titles, save_markdown, ws};
use models::DbState;
use mongodb::{
    bson::doc, options::ClientOptions, options::IndexOptions, Client, Collection, IndexModel,
};
use utils::{env_host, env_mongo_uri, env_port, initialize_mongo_client};

#[post("/build_chroma")]
async fn build_chroma() -> impl actix_web::Responder {
    Redirect::to("http://127.0.0.1:5000/build_chroma").permanent()
}
#[post("/ask")]
async fn ask() -> impl actix_web::Responder {
    Redirect::to("http://127.0.0.1:5000/ask").permanent()
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    dotenv().ok();

    let mongo_client = initialize_mongo_client(&env_mongo_uri()).await;

    HttpServer::new(move || {
        App::new()
            .app_data(web::Data::new(DbState {
                client: mongo_client.clone(),
            }))
            .wrap(Logger::default())
            .service(ws)
            .service(save_markdown)
            .service(get_markdown_titles)
            .service(delete_markdown)
            .service(build_chroma)
            .service(ask)
            .service(get_markdown)
    })
    .bind(format!("{}:{}", env_host(), env_port()))?
    .run()
    .await?;

    Ok(())
}
